﻿using System;
using System.Text.RegularExpressions;

namespace Util.TitleParser
{
    //Format 118 & 1218
    class Parse_see : ITitleParser
    {
        public Result ParseTitle(string title)
        {
            string Name, Details;
            long Season, Episode;

            int firstLetterAdjustment;
            Match m = Regex.Match(title, ".[0-9][0-3][0-9]");
            while(m.Success)
            {
                if (m.Value[0] != '0' && m.Value[0] != '1' && m.Value[0] != '2')
                {
                    firstLetterAdjustment = 1;
                }
                else if (char.IsDigit(m.Value[0])) //3-9 are impossible since no show has >= 30 seasons
                {
                    m = m.NextMatch();
                    continue;
                }
                else
                {
                    firstLetterAdjustment = 0;
                }

                Season = long.Parse(m.Value.Substring(firstLetterAdjustment, 2 - firstLetterAdjustment), System.Globalization.CultureInfo.InvariantCulture);
                Episode = long.Parse(m.Value.Substring(2, 2), System.Globalization.CultureInfo.InvariantCulture);

                if ((Season == 10 && Episode == 80) //1080p, probably not a episode number
                    || ((Season == 7 && Episode == 20) && (m.Index + 4 >= title.Length || title[m.Index + 4] == 'p' || title[m.Index + 4] == 'P')) //720p, probably not a episode number
                    || (Season == 20 && Episode <= 9) || (Season == 19 && Episode >= 40) //Probably a year, not a episode number
                    )
                {
                    m = m.NextMatch();
                }
                else
                {
                    Name = title.Substring(0, m.Index - 1 + firstLetterAdjustment);

                    if(m.Index + 4 < title.Length)
                    {
                        Details = title.Substring(m.Index + 4);
                    }
                    else
                    {
                        Details = title;
                    }
                    return new Result(Name, Details, Season, Episode);
                }
            }
            return null;
        }
    }
}
